package com.qos.fun;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

import com.qos.http.AsyncHttpClient;
import com.qos.http.AsyncHttpResponseHandler;
import com.qos.http.RequestParams;

import org.json.JSONObject;
import org.json.JSONTokener;

public class ConnectManager extends Service {

    private static final String LOG = "connectManager";

    private static final String rootUrl = "http://10.4.65.59/";
    private String registUrl = rootUrl + "regist/registcommit/";
    private String loginUrl = rootUrl + "regist/login/";
    private String logoutUrl = rootUrl + "regist/logout/";
    private String queueQueryUrl = rootUrl + "mysession/queryRestaurantQueueInfo/";
    private String queueOrderUrl = rootUrl + "mysession/requestapassport/";
    private String OrderStartUrl = rootUrl + "mysession/orderstart/";

    static final int MSG_REGIST = 1;
    static final int MSG_LOGIN = 2;
    static final int MSG_LOGOUT = 3;
    static final int MSG_QUEUE_QUERY = 4;
    static final int MSG_QUEUE_ORDER = 5;
    
    AsyncHttpClient client = new AsyncHttpClient();
    Messenger actM;
    Bundle data;
    /**
     * Handler of incoming messages from clients.
     */
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            RequestParams rp = new RequestParams();
            actM = msg.replyTo;
            switch (msg.what) {
                case MSG_REGIST:
                	Log.d(LOG,"regist");
                    data = msg.getData();
                    rp.put("username", data.getString("username"));
                    rp.put("password", data.getString("passwd"));
                    rp.put("email", data.getString("mail"));
                    client.post(registUrl, rp, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String response) {
                        	try {
	                            JSONTokener tokener = new JSONTokener(response);
	                            JSONObject jsb = new JSONObject(tokener);
	                            Log.d(LOG, "response is : "+jsb.getInt("result"));
	                            int result = jsb.getInt("result");
	                            Message actMsg = Message.obtain(null,MSG_REGIST,result);
								actM.send(actMsg);
							} catch (Exception e) {
								Log.d(LOG,"Exception :"+e.toString());
							}
                        }
                    });
                    break;
                case MSG_LOGIN:
                    Log.d(LOG,"login");
                    data = msg.getData();
                    rp.put("username", data.getString("username"));
                    rp.put("password", data.getString("passwd"));
                    client.post(loginUrl, rp, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String response) {
                         	try {
	                            JSONTokener tokener = new JSONTokener(response);
	                            JSONObject jsb = new JSONObject(tokener);
	                            Log.d(LOG, "response is : "+jsb.getInt("result"));
	                            int result = jsb.getInt("result");
	                            Message actMsg = Message.obtain(null,MSG_LOGIN,result);
								actM.send(actMsg);
							} catch (Exception e) {
								Log.d(LOG,"Exception :"+e.toString());
							}
                        }
                    });
                    break;
                case MSG_QUEUE_QUERY:
                    Log.d(LOG,"queue query :"+queueQueryUrl);
                    rp.put("restaurantid", "1");
                    client.post(queueQueryUrl, rp, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String response) {
                            try {
                                Log.d(LOG, "queue query : "+ response);
                                JSONTokener tokener = new JSONTokener(response);
                                JSONObject jsb = new JSONObject(tokener);
                                Log.d(LOG, "response is : "+jsb.getInt("error"));
                                int result = jsb.getInt("error");
                                JSONObject userData = jsb.getJSONObject("userdata");
                                Bundle data = new Bundle();
                                data.putString("queuestartflag", userData.getString("queuestartflag"));
                                data.putString("queuenextcallnum", userData.getString("queuenextcallnum"));
                                data.putString("queuenextdistributenum", userData.getString("queuenextdistributenum"));
                                Message actMsg = Message.obtain(null,MSG_QUEUE_QUERY,result);
                                actMsg.setData(data);
                                actM.send(actMsg);
                            } catch (Exception e) {
                                Log.d(LOG,"Exception :"+e.toString());
                            }
                        }
                    });
                    break;
                case MSG_QUEUE_ORDER:
                    Log.d(LOG,"queue order :"+queueOrderUrl);
                    rp.put("restaurantid", "1");
                    client.post(OrderStartUrl, rp, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String response) {
                            RequestParams rp2 = new RequestParams();
                            rp2.put("restaurantid", "1");
                            client.post(queueOrderUrl, rp2, new AsyncHttpResponseHandler() {
                                @Override
                                public void onSuccess(String response) {
                                    try {
                                        Log.d(LOG, "queue order : "+ response);
                                        JSONTokener tokener = new JSONTokener(response);
                                        JSONObject jsb = new JSONObject(tokener);
                                        Log.d(LOG, "response is : "+jsb.getInt("error"));
                                        int result = jsb.getInt("error");
                                        /*
                                        JSONObject userData = jsb.getJSONObject("userdata");
                                        Bundle data = new Bundle();
                                        data.putString("queuestartflag", userData.getString("queuestartflag"));
                                        data.putString("queuenextcallnum", userData.getString("queuenextcallnum"));
                                        data.putString("queuenextdistributenum", userData.getString("queuenextdistributenum"));
                                        */
                                        Message actMsg = Message.obtain(null,MSG_QUEUE_ORDER,result);
                                        //actMsg.setData(data);
                                        actM.send(actMsg);
                                    } catch (Exception e) {
                                        Log.d(LOG,"Exception :"+e.toString());
                                    }
                                }
                            });
                        }
                    });
                    
                    break;
                case MSG_LOGOUT:
                    Log.d(LOG,"logout");
                    client.post(logoutUrl, rp, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String response) {
                            try {
                                Message actMsg = Message.obtain(null,MSG_LOGOUT);
                                actM.send(actMsg);
                            } catch (Exception e) {
                                Log.d(LOG,"Exception :"+e.toString());
                            }
                        }
                    });
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
    
    /**
     * Target we publish for clients to send messages to IncomingHandler.
     */
    final Messenger mMessenger = new Messenger(new IncomingHandler());
    
    @Override
    public void onCreate() {
    }

    @Override
    public void onDestroy() {
    }
    
    /**
     * When binding to the service, we return an interface to our messenger
     * for sending messages to the service.
     */
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }


}
